from time import sleep
import login_info.login_info as login
import requests
from requests.cookies import RequestsCookieJar
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import tools.log_op as log
class get_login_cookie():
    def __init__(self,get_cookie_url,emr_user,emr_password,flag='studio'):
        self.xsr =''
        self.head_cookie=''
        self.get_brower_cookies(get_cookie_url, emr_user, emr_password, flag)
        print(1)
    def get_brower_cookies(self,get_cookie_url,emr_user,emr_password,flag='studio'):
        chrome_options = webdriver.ChromeOptions()
        # chrome_options.add_argument('--headless')
        # chrome_options.add_argument('--disable-gpu')
        # chrome_options.add_argument('--no-sandbox')
        # chrome_options.add_argument('--hide-scrollbars')
        browser = webdriver.Chrome(options=chrome_options)
        browser.implicitly_wait(5)
        browser.get(get_cookie_url)
        WebDriverWait(browser, 10).until(EC.visibility_of(browser.find_element_by_id('login-by')))
        login_name = browser.find_element_by_id('login-by')
        login_name.send_keys(emr_user)
        WebDriverWait(browser, 10).until(EC.visibility_of(browser.find_element_by_id('password')))
        login_psd = browser.find_element_by_id('password')
        login_psd.send_keys(emr_password)

        login_btn = browser.find_element_by_id('btn-submit-login')
        login_btn.click()

        simi = browser.find_element_by_id('details-button')
        simi.click()
        go = browser.find_element_by_id('proceed-link')
        go.click()
        sleep(1)
        if(flag=='studio'):
            browser_cookie = browser.get_cookies()
            cookie_name = browser_cookie[0]['name']
            cookie_value = browser_cookie[0]['value']
            head_cookie = f'{cookie_name}={cookie_value}'
            print(head_cookie)
            print('登陆网站获取cookie: ',head_cookie)
            self.head_cookie = head_cookie
            log.put_cookies_in_txt(head_cookie)
            browser.close()
        if(flag=='river'):
            browser_cookie = browser.get_cookies()
            cookie_name = browser_cookie[0]['name']
            cookie_value = browser_cookie[0]['value']
            cookie_name_1 = browser_cookie[1]['name']
            cookie_value_1 = browser_cookie[1]['value']
            head_cookie = f'{cookie_name}={cookie_value}; {cookie_name_1}={cookie_value_1}'
            self.head_cookie = head_cookie
            self.xsr = browser_cookie[1]['value']
            info = {'head':self.head_cookie,'xsr':self.xsr}
            log.pub_cookies_in_json(info)
            browser.close()

        return head_cookie
if __name__ == '__main__':
    a = get_login_cookie(login.river_get_cookie_url,login.emr_user,login.emr_password,'river')
